package com.myrice.jms.impl;

import java.nio.ByteBuffer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import com.myrice.jms.MessageFactory;
import com.myrice.jms.MsgRequest;
import com.myrice.jms.MsgSession;

public class DefaultMessageFactory implements MessageFactory {
	private static final int CAPACITY = 50;

	private BlockingQueue<DefaultMessage> queue = new ArrayBlockingQueue<DefaultMessage>(
			CAPACITY);

	public void recycle(DefaultMessage message) {
		queue.offer(message);// 回收资源
	}

	public DefaultMessage newInstance() {
		DefaultMessage instance = popInstance();
		if (instance == null) {
			instance = newMessage();
		}
		return instance;
	}

	protected DefaultMessage newMessage() {
		return new DefaultMessage();
	}

	public DefaultMessage popInstance() {
		return queue.poll();
	}

	public MsgRequest create(MsgSession session, ByteBuffer msg) {
		DefaultMessage message = newInstance();
		message.init((DefaultMsgSession) session, msg);
		return message;
	}

	public ByteBuffer encode(MsgSession session, byte type, int mode,
			ByteBuffer msg) {
		ByteBuffer packet = onSendBefore(session, msg);

		packet.put(type) // 0 响应 1 请求(1 byte)
				.putInt(mode); // int 标识(4 byte)

		onSendAfter(session, packet, msg);

		packet.flip();
		return packet;
	}

	protected void onSendAfter(MsgSession session, ByteBuffer packet,
			ByteBuffer msg) {
		packet.put(msg);// 数据内容
	}

	protected ByteBuffer onSendBefore(MsgSession session, ByteBuffer msg) {
		int length = 5 + msg.remaining() + 8;
		msg = ByteBuffer.allocate(length);
		return msg;
	}
}
